﻿using System.Collections.Generic;
using System.Linq;
using KaytechSoftware.Cms.Entities;
using KaytechSoftware.Cms.Entities.Interfaces;
using KaytechSoftware.Cms.Services.Dto;
using KaytechSoftware.Cms.Services.Interfaces.Entity;

namespace KaytechSoftware.Cms.Services.Services.Entity
{
    public class NewsService : OrderedEntityBaseService<News, NewsDto>, INewsService
    {
        private readonly IRepository<Page> _pageRepository;

        public NewsService(IUnitOfWorkService unitOfWorkService, IRepository<News> newsService, IRepository<Page> pageRepository) : base(unitOfWorkService, newsService)
        {
            _pageRepository = pageRepository;
        }

        public override void Save(NewsDto dto)
        {
            using (var unitOfWork = UnitOfWorkService.Create())
            {
                var news = GetInstance(dto.Id);
                news.Title = dto.Title;
                news.Body = dto.Body;
                news.Page = _pageRepository.GetById(dto.PageId);
                news.Order = 1;

                Store(news);
                unitOfWork.Commit();
            }
        }

        public override IList<NewsDto> GetAll()
        {
            using (UnitOfWorkService.Create())
            {
                var news = EntityRepository.GetAll(n => n.Page).ToList();
                return news.Select(n => new NewsDto(n)).ToList();
            }
        }

        public IList<NewsDto> GetAllForPage(long pageId)
        {
            using (UnitOfWorkService.Create())
            {
                var news = EntityRepository.GetAll(n => n.Page).Where(n => n.Page.Id == pageId).OrderByDescending(n => n.Order).ToList();
                return news.Select(n => new NewsDto(n)).ToList();
            }
        }

        protected override IQueryable<News> LimitEntitiesForOrdering(News promotedEntity)
        {
            return EntityRepository.GetAll().Where(n => n.PageId == promotedEntity.PageId);
        }
    }
}
